<?php

namespace app\admin\controller\tools;

use app\admin\controller\Base;
use think\facade\Request;
use think\facade\View;



class Develop extends Base{
    protected $model,$applist;
    public function initialize()
    {
        parent::initialize();
        $this->applist = [
            [
                'name' => 'admin',
                'label' => '后台[admin]'
            ],
//            [
//                'name' => 'user',
//                'label' => '前台[user]'
//            ]
        ];
        View::assign(['applist'=>$this->applist]);
    }

    public function build(){
        if (Request::isPost()){
            $data = $this->request->post();
            if (empty($data['type'])){
                $this->error('内容必须选择一项');
            }
            $appName = $data['app'];
            $type = $data['type'];

            // 创建控制器和模型 二者一一对应，否者生成的控制器会出错
            if ($type == 'controller'){
                $controllerName = $data['name'];
                $res = $this->makeModel($appName,$controllerName);
                if ($res['code'] == 0){
                    $this->error('模型创建失败：'.$res['msg']);
                }
                $res = $this->makeController($appName,$controllerName,$res['modelPath']);
                if ($res['code'] == 0){
                    $this->error('控制器创建失败：'.$res['msg']);
                }
            }
//            // 创建模型
//            if ($type == 'controller'){
//                $controllerName = $data['name'];
//                $res = $this->makeModel($appName,$controllerName);
//                if ($res['code'] == 0){
//                    $this->error('模型创建失败：'.$res['msg']);
//                }
//                $res = $this->makeController($appName,$controllerName,$res['modelPath']);
//                if ($res['code'] == 0){
//                    $this->error('控制器创建失败：'.$res['msg']);
//                }
//            }
            // 创建验证器
            if ($type == 'validate'){
                $controllerName = $data['name'];
                $res = $this->makeValidate($appName,$controllerName);
                if ($res['code'] == 0){
                    $this->error('验证器创建失败：'.$res['msg']);
                }
            }
            $this->success('创建成功');
        }

        return view();
    }

    /**
     * 生成控制器
     * @param string $appName
     * @param string $controllerName
     * @param $modelPath
     */
    public function makeController($appName='', $controllerName='',$modelPath=''){
        $result = [];
        try{
            $controllerTpl = app()->getRootPath() . 'app/common/tpl/controller.tpl';
            $controllerTplContent = file_get_contents($controllerTpl);

            $parseRes = $this->parseName($controllerName);
            $secDir = $parseRes['secDir'];
            $controllerName = $parseRes['controllerName'];

            $nameSpace = "app\\{$appName}\\controller{$secDir}";
            $controllerPath = "\\{$nameSpace}\\".ucfirst($controllerName);

            if (class_exists($controllerPath)){
                $this->error('控制器已存在');
            }
            $filePath = app()->getRootPath() .$nameSpace;
            $this->checkDirs($filePath);

            // 生成控制器
            $old_arr = ['$namspace','$controller', '$app','$modelPath'];
            $rpl_arr = [$nameSpace, ucfirst($controllerName), strtolower($appName),$modelPath];
            $controllerTpl = str_replace($old_arr, $rpl_arr, $controllerTplContent);
            file_put_contents( app()->getRootPath() . $nameSpace ."\\". ucfirst($controllerName) . '.php', $controllerTpl);
            $result = ['code'=>1,'msg'=>'创建成功'];
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            $result = ['code'=>0,'msg'=>$e->getMessage()];
        }
        return $result;

    }
    /**
     * 生成模型
     * @param string $appName
     * @param string $controllerName
     */
    public function makeModel($appName='', $controllerName=''){
        $result = [];
        try{
            $modelTpl = app()->getRootPath() . 'app/common/tpl/model.tpl';
            $modelTplContent = file_get_contents($modelTpl);

            $parseRes = $this->parseName($controllerName);
            $secDir = $parseRes['secDir'];
            $controllerName = $parseRes['controllerName'];


            $nameSpace = "app\\{$appName}\\model{$secDir}";
            $modelPath = "\\$nameSpace\\".ucfirst($controllerName);

            if (class_exists($modelPath)){
                $this->error('模型已存在');
            }
            $filePath = app()->getRootPath() .$nameSpace;
            $this->checkDirs($filePath);

            // 生成模型
            $old_arr = ['$namspace','$controller'];
            $rpl_arr = [$nameSpace, ucfirst($controllerName)];
            $modelTpl = str_replace($old_arr, $rpl_arr, $modelTplContent);
            file_put_contents( app()->getRootPath() . $nameSpace ."\\". ucfirst($controllerName) . '.php', $modelTpl);

            $result = ['code'=>1,'msg'=>'创建成功','modelPath'=>$modelPath];
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            $result = ['code'=>0,'msg'=>$e->getMessage()];
        }
        return $result;

    }
    /**
     * 生成验证器
     * @param string $appName
     * @param string $controllerName
     */
    public function makeValidate($appName='', $controllerName=''){
        $result = [];

        try{
            $validateTpl = app()->getRootPath() . 'app/common/tpl/validate.tpl';
            $validateTplContent = file_get_contents($validateTpl);

            $parseRes = $this->parseName($controllerName);
            $secDir = $parseRes['secDir'];
            $controllerName = $parseRes['controllerName'];
            $nameSpace = "app\\{$appName}\\validate{$secDir}";
            $validatePath = "\\$nameSpace\\".ucfirst($controllerName);

            if (class_exists($validatePath)){
                $this->error('验证器已存在');
            }
            $filePath = app()->getRootPath() .$nameSpace;
            $this->checkDirs($filePath);

            $old_arr = ['$namspace','$controller'];
            $rpl_arr = [$nameSpace, ucfirst($controllerName)];
            $validateTpl = str_replace($old_arr, $rpl_arr, $validateTplContent);
            file_put_contents( app()->getRootPath() . $nameSpace ."\\". ucfirst($controllerName) . '.php', $validateTpl);

            $result = ['code'=>1,'msg'=>'创建成功'];
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            $result = ['code'=>0,'msg'=>$e->getMessage()];
        }
        return $result;
    }

    private function parseName($controllerName){
        $secDir = '';
        if (strpos($controllerName, '.')) {
            // 解析多层目录
            [$secDir, $controllerName] = explode('.', $controllerName);
            $secDir = "\\{$secDir}";
        }
        return [
            "secDir" => $secDir,
            "controllerName" => $controllerName
        ];
    }

    /**
     * 创建目录
     */
    private function checkDirs($filePath){
        if (!is_dir($filePath)) {
            mkdir($filePath, 0755, true);
            chmod($filePath, 0755);
        }
    }



}